import { useEffect } from "react";
import { useReactive } from "ahooks";
import { notification } from "antd";
import dayjs from "dayjs";

const { ipcRenderer } = electron;

export default function globalModel() {
    let state = useReactive({
        isMaximized: true,
        currentWindow: remote.getCurrentWindow(),
        windowInnerHeight: window.innerHeight,
    });

    window.onresize = () => {
        state.windowInnerHeight = window.innerHeight;
    };

    useEffect(() => {
        const remoteSharedObject = remote.getGlobal("sharedObject");
        for (let key in remoteSharedObject) {
            state[key] = remoteSharedObject[key];
        }

        if (state.currentWindow) {
            state.currentWindow.on("maximize", () => {
                state.isMaximized = state.currentWindow.isMaximized();
            });

            state.currentWindow.on("unmaximize", () => {
                state.isMaximized = state.currentWindow.isMaximized();
            });
        }
    }, []);

    const UTCTimeToLocal = (time, format = "YYYY-MM-DD HH:mm:ss") => {
        if (!time) return "";
        let localTime = new Date().UTCTimeToLocal(time);
        if (format) return dayjs(localTime).format(format);
        return localTime;
    };

    const remoteData = async (options) => {
        options.organizationUuid = options.organizationUuid || window.organizationUuid;
        let response = await httpRequest(options);
        if (response.statusCode === 0) {
            return response.result ? response.result : true;
        } else if (response.statusCode === 1) {
            let msgs = [response.message];
            if (Array.isArray(response.result)) msgs = msgs.concat(response.result);
            if (typeof response.result === "string") msgs.push(response.result);
            notification.error({ message: "登录过期了", description: msgs.join("；") });
            return null;
        } else if (response.statusCode >= 400) {
            let msgs = [response.message];
            if (Array.isArray(response.result)) msgs = msgs.concat(response.result);
            if (typeof response.result === "string") msgs.push(response.result);
            notification.error({ message: "错误信息", description: msgs.join("；") });
            return null;
        } else {
            return null;
        }
    };

    const graphqlFetch = async (params) => {
        if (window.organizationUuid) {
            let serviceName = params.serviceName || "allinone";
            return await remoteData({
                object: "multi-organization-gateway",
                serviceName: `/graphql/${serviceName}_graphql_service`,
                organizationUuid: window.organizationUuid,
                params,
            });
        }
    };

    const openWindow = (winID, url, options = {}) => {
        let newOptions = JSON.parse(JSON.stringify(options));
        ipcRenderer.send("open-window", { winID, url, ...newOptions });
    };

    const transTree = (jsonData, id, parentID, children = "children") => {
        if (!Array.isArray(jsonData)) return [];
        if (jsonData.length === 0) return [];

        //result存储json数据转为树形结构后的结果。
        //temp为临时对象，将json数据按照id值排序.
        //len是json长度，用于循环遍历结束的条件
        var result = [],
            temp = {},
            len = jsonData.length;
        for (var i = 0; i < len; i++) {
            if (!jsonData[i]) continue;
            // 以id作为索引存储元素，可以无需遍历直接快速定位元素
            temp[jsonData[i][id]] = jsonData[i];
        }
        for (var j = 0; j < len; j++) {
            if (!jsonData[j]) continue;
            var currentElement = jsonData[j];
            // 临时变量里面的当前元素的父元素，即pid的值，与找对应id值
            var tempCurrentElementParent = temp[currentElement[parentID]];
            // 如果存在父元素，即如果有pid属性
            if (tempCurrentElementParent) {
                // 如果父元素没有chindren键
                if (!tempCurrentElementParent[children]) {
                    // 设上父元素的children键
                    tempCurrentElementParent[children] = [];
                }
                // 给父元素加上当前元素作为子元素
                tempCurrentElementParent[children].push(currentElement);
            }
            // 不存在父元素，意味着当前元素是一级元素
            else {
                result.push(currentElement);
            }
        }
        return result;
    };

    const numberFormat = (number, decimals = 2, decPoint = ".", thousandsSep = ",", roundtag) => {
        /*
         * 参数说明：
         * number：要格式化的数字
         * decimals：保留几位小数
         * dec_point：小数点符号
         * thousands_sep：千分位符号
         * roundtag:舍入参数，默认 'ceil' 向上取,'floor'向下取,'round' 四舍五入
         * */
        number = (number + "").replace(/[^0-9+-Ee.]/g, "");
        roundtag = roundtag || "ceil"; // 'ceil','floor','round'
        var n = !isFinite(+number) ? 0 : +number;
        var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals);
        var sep = typeof thousandsSep === "undefined" ? "," : thousandsSep;
        var dec = typeof decPoint === "undefined" ? "." : decPoint;
        var s = "";
        var toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return "" + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)) / k;
        };
        s = (prec ? toFixedFix(n, prec) : "" + Math.round(n)).split(".");
        var re = /(-?\d+)(\d{3})/;
        while (re.test(s[0])) {
            s[0] = s[0].replace(re, "$1" + sep + "$2");
        }

        if ((s[1] || "").length < prec) {
            s[1] = s[1] || "";
            s[1] += new Array(prec - s[1].length + 1).join("0");
        }
        return s.join(dec);
    };

    return { ...state, remoteData, UTCTimeToLocal, openWindow, graphqlFetch, transTree, numberFormat };
}
